﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Revis.VClinicNet.UI.External.Client.View;
using Revis.VClinicNet.UI.External.Client.Service;
using System.Collections.ObjectModel;

namespace Revis.VClinicNet.UI.External.Client.ViewModel
{
    public class VisitsViewModel : WorkspaceControlViewModelBase<Visits>
    {
        public VisitsViewModel()
        {
            _visitsList = new ReadOnlyCollection<VisitDto>(new List<VisitDto>());
        }

        public override void Run()
        {
            Request();
        }

        public void Request()
        {
            ChangeState("Pobieranie przyszłych wizyt", RequestState.Requesting);
            _patientService.BeginVisits(new AsyncCallback(RequestEnded), null);
        }

        public void RequestEnded(IAsyncResult result)
        {
            try {
                VisitDto[] visits = _patientService.EndVisits(result)
                    .OrderBy(v => v.Date)
                    .ToArray();
                VisitsList = new ReadOnlyCollection<VisitDto>(visits);
                ChangeState("Wizyty zostały pobrane", RequestState.Success);
            } catch (Exception) {
                ChangeState("Wystąpił poważny błąd podczas pobierania listy wizyt", RequestState.Faulted);
            }
        }

        private ReadOnlyCollection<VisitDto> _visitsList;
        public ReadOnlyCollection<VisitDto> VisitsList
        {
            get { return _visitsList; }
            set
            {
                _visitsList = value;
                RaisePropertyChanged("VisitsList");
            }
        }
    }
}
